
import React from 'react'
import { connect } from 'react-redux'
import { addTaskAction } from './Store/actions'

class Header extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      etitle: ''
    }
  }

  handleEtitle = (e) => {
    this.setState({
      etitle: e.target.value
    })
  }

  handleKeyup = (e) => {
    // 回车键的数字标识是13
    if (e.keyCode === 13) {
      console.log(3)
      // 按了回车键,添加任务,把任务名称传递到父组件即可
      this.props.addTask(this.state.etitle)
      // 清空表单
      this.setState({
        etitle: ''
      })
    }
  }

  render() {
    const { addTast } = this.props
    return (
      <div>
        <header className="header">
          <h1>Todo List</h1>
          <input onKeyUp={addTast} value={this.state.etitle} onChange={this.handleEtitle} className="new-todo" placeholder="你想做什么?" />
        </header>
      </div>
    )
  }
}

const mapDispatchToProps = (dispatch) => {
  const addTast = (e) => {
    // 回车键的数字标识是13
    if (e.keyCode === 13) {
      // 创建添加任务的 action
      let action = addTaskAction(e.target.value)
      // 分发 action
      dispatch(action)
      // 清空输入框
      e.target.value = ''
    }
  }

  return {
    addTast
  }
}

export default connect(null, mapDispatchToProps)(Header)